package com.picket.controller;

import java.util.Calendar;
import java.util.Collection;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Required;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.picket.ResourceNotFoundException;
import com.picket.domain.Event;
import com.picket.service.IEventService;

@Controller
@RequestMapping(value="/admin/event")
public class EventController {
	private IEventService eventService;
	
	@Required
	public void setEventService(
			IEventService eventService) {
		this.eventService = eventService;
	}

	@RequestMapping(value="/create",method=RequestMethod.GET)
	public String getCreateForm(Model model) {
		model.addAttribute(new Event());
		return "/event/createForm";
	}
	
	@RequestMapping(value="/create",method=RequestMethod.POST)
	public String create(@Valid Event event, BindingResult result) {
		if (result.hasErrors()) {
			return "/event/createForm";
		}
		event.setStartDate(Calendar.getInstance().getTime());
		event.setEndDate(Calendar.getInstance().getTime());
		eventService.create(event);
		return "redirect:/admin/event/all";
	}
	
	@RequestMapping(value="{id}", method=RequestMethod.GET)
	public String getView(@PathVariable Long id, Model model) {
		Collection<Event> events = eventService.getAllEvents();
		if (events == null) {
			throw new ResourceNotFoundException(id);
		}
		Event evt = eventService.getEvent(id);
		model.addAttribute("event", evt);
		return "/event/view";
	}
	
	@RequestMapping(value="/all", method=RequestMethod.GET)
	public String doShowAll(Model model) {
		Collection<Event> events = eventService.getAllEvents();
		model.addAttribute("allEvents", events);
		return "/event/viewall";
	}

}
